import Vue from 'vue'
import VueRouter from 'vue-router'
import homepageCom from '@/views/homepage/homepageCom.vue'
import loginCom from '@/views/login/loginCom.vue'
import searchCom from '@/views/searchCom/searchCom.vue'
import searchList from '@/views/searchList/searchList.vue'
import commodityCom from '@/views/commodity/commodityCom.vue'
import payCom from '@/views/pay/payCom.vue'
import ordersCom from '@/views/orders/ordersCom.vue'
import home from '@/views/homepage/home.vue'
import fenlei from '@/views/homepage/fenlei.vue'
import shop from '@/views/homepage/shop.vue'
import mine from '@/views/homepage/mine.vue'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: homepageCom,
    redirect: '/home',
    children: [
      {
        path: '/home',
        component: home
      },
      {
        path: '/fenlei',
        component: fenlei
      },
      {
        path: '/shop',
        component: shop
      },
      {
        path: '/mine',
        component: mine
      }
    ]
  },
  {
    path: '/login',
    component: loginCom
  },
  {
    path: '/search',
    component: searchCom
  },
  {
    path: '/searchList',
    component: searchList
  },
  {
    path: '/commodity',
    component: commodityCom
  },
  {
    path: '/pay',
    component: payCom
  },
  {
    path: '/orders',
    component: ordersCom
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 全局前置导航守卫
const authUrls = ['/pay', '/orders']
router.beforeEach((to, from, next) => {
  if (!authUrls.includes(to.path)) {
    // 非权限页面直接放行
    next()
  }
  const token = store.state.user.userinfo.token
  if (token) {
    next()
  } else {
    next('/login')
  }
})

export default router
